package com.java.web.listener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListener implements HttpSessionListener{

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		HttpSession session=se.getSession();
		String sessionId=session.getId();
		//获得应用上下文
		ServletContext servletContext=session.getServletContext();
		List<HttpSession> originalSessionList=(List<HttpSession>)servletContext.getAttribute("sessionList");
		List<HttpSession> sessionList=originalSessionList==null?new ArrayList<HttpSession>():originalSessionList;
		sessionList.add(session);
		servletContext.setAttribute("sessionList", sessionList);
		System.out.println("新的session被创建，其sessionId为："+sessionId);
		System.out.println("session信息："+"sessionId="+session.getId()+",\nsession创建时间="+new Date(session.getCreationTime())+",\nsession最后访问时间="+new Date(session.getLastAccessedTime())+",\nsession过期时间="+session.getMaxInactiveInterval()+",\nsession是否是新的="+session.isNew());
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		HttpSession session=se.getSession();
		String sessionId=session.getId();
		//获得应用上下文
		ServletContext servletContext=session.getServletContext();
		List<HttpSession> sessionList=new ArrayList<HttpSession>();
		sessionList.remove(session);
		servletContext.setAttribute("sessionList", sessionList);
		System.out.println("session被销毁，其sessionId为："+sessionId);
		System.out.println("session信息："+"sessionId="+session.getId()+",\nsession创建时间="+new Date(session.getCreationTime())+",\nsession最后访问时间="+new Date(session.getLastAccessedTime())+",\nsession过期时间="+session.getMaxInactiveInterval()+",\nsession是否是新的="+session.isNew());
		
	}

}
